package com.senjoeson.teamfriends.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.senjoeson.teamfriends.R;
import com.senjoeson.teamfriends.adapter.MyPagerAdapter;
import com.senjoeson.teamfriends.base.App;
import com.senjoeson.teamfriends.bean.Friend;
import com.senjoeson.teamfriends.bean.FriendMessage;
import com.senjoeson.teamfriends.bean.Message;
import com.senjoeson.teamfriends.bean.MessageTypeUtils;
import com.senjoeson.teamfriends.bean.User;
import com.senjoeson.teamfriends.fragment.FriendFragment;
import com.senjoeson.teamfriends.fragment.HobbiesFragment;
import com.senjoeson.teamfriends.fragment.NeigborFragment;
import com.senjoeson.teamfriends.utils.ALog;
import com.senjoeson.teamfriends.utils.GlideUtils;
import com.senjoeson.teamfriends.utils.ImageUtils;
import com.senjoeson.teamfriends.utils.MyToast;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobRealTimeData;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.bmob.v3.listener.ValueEventListener;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tablayout)
    TabLayout mTablayout;
    @BindView(R.id.viewpager)
    ViewPager mViewpager;
    @BindView(R.id.fab)
    FloatingActionButton mFab;
    @BindView(R.id.nav_view)
    NavigationView mNavView;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    public String[] mTabTitles;

    public LocationClient mLocationClient = null;

    private MyLocationListener myListener = new MyLocationListener();


    private TabLayout.OnTabSelectedListener mOnTabSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mToolbar.setTitle(mTabTitles[tab.getPosition()]);
            mViewpager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
    private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            mTablayout.setScrollPosition(position, positionOffset, true);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };
    public ImageView mPortrait;
    public TextView mNickName;
    public TextView mSign;
    public LatLng mLatLng;
    public Dialog mAlertDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(App.ThemeControl ? R.style.AppTheme : R.style.AppTheme_Black);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        checkLogin();

    }

    private void initView() {
        setSupportActionBar(mToolbar);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        View headerView = mNavView.getHeaderView(0);
        mPortrait = headerView.findViewById(R.id.portrait);
        mNickName = headerView.findViewById(R.id.nickname);
        mSign = headerView.findViewById(R.id.sign);
        initData();
    }

    /**
     * 检查登录的逻辑
     */
    private void checkLogin() {
        //检查登陆逻辑
        User currentUser = BmobUser.getCurrentUser(User.class);
        if (currentUser == null) {
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        } else {
            checkIsNotNewMessage(); //检测你是否有人给你发消息
            loadData();
            initView();

            mNavView.setNavigationItemSelectedListener(this);
            mFab.setOnClickListener(this);
            mLocationClient = new LocationClient(getApplicationContext());
            //声明LocationClient类
            mLocationClient.registerLocationListener(myListener);
            //注册监听函数
            LocationClientOption option = new LocationClientOption();
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
            option.setCoorType("bd09ll");
            option.setScanSpan(1000);
            option.setOpenGps(true);
            option.setLocationNotify(true);
            option.setIgnoreKillProcess(false);
            option.SetIgnoreCacheException(false);
            option.setEnableSimulateGps(false);
            mLocationClient.setLocOption(option);
            mLocationClient.start();

        }
    }

    /**
     * 检查是否有新消息
     */
    private void checkIsNotNewMessage() {
        User currentUser = BmobUser.getCurrentUser(User.class);
        String userId = currentUser.getObjectId();
        BmobQuery<Message> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("other_userid", userId);
        bmobQuery.order("createdAt");
        bmobQuery.findObjects(new FindListener<Message>() {
            @Override
            public void done(List<Message> list, BmobException e) {
                if (list != null && list.size() > 0) {
                    ALog.d(list.size() + "");
                    Message message = list.get(0);
                    int messageType = message.getMessageType();

                    resolveState(message, messageType);

                } else {
                    ALog.d("没有新消息");
                }
            }
        });
    }


    /**
     * 设置页面的透明度
     *
     * @param bgAlpha 1表示不透明
     */
    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    private void resolveState(final Message message, final int messageType) {

        View inflateView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_window, null, false);
        final PopupWindow popupWindow = new PopupWindow(inflateView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        //   popupWindow.setContentView(inflateView);
        popupWindow.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(-00000);
        popupWindow.setBackgroundDrawable(dw);
        setBackgroundAlpha(MainActivity.this, 1f);
        popupWindow.setAnimationStyle(R.anim.anim);
        TextView mContent = inflateView.findViewById(R.id.content);
        TextView mTitle = inflateView.findViewById(R.id.title);
        Button mConfirm = inflateView.findViewById(R.id.confirm);
        Button mCancel = inflateView.findViewById(R.id.cancel);
        mTitle.setText("");
        SpannableString spanString = new SpannableString(message.getNickname());
        ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary));
        spanString.setSpan(span, 0, spanString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //  String format = String.format("来自%s的消息来了", spanString);
        mTitle.append("来自");
        mTitle.append(spanString);
        mTitle.append("的消息来了");


        //  AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        String content = "";
        switch (messageType) {
            case MessageTypeUtils.MESSGE_HELP:
                content = "你的好友请求求助，请赶紧去查看吧";

                break;
            case MessageTypeUtils.MESSGE_APPLY_FRIEND_STATE:
                content = "你的好友向你发送一条好友申请";

                break;
            case MessageTypeUtils.MESSGE_APPLY_FRIEND_REFUSE:
                content = "你的好友请求已被拒绝";

                break;
            case MessageTypeUtils.MESSGE_APPLY_FRIEND_PASS:
                content = "你的好友请求已被通过";
                break;
        }
        mContent.setText(content);


        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {       //去看看
                if (messageType == MessageTypeUtils.MESSGE_HELP) {
                    popupWindow.dismiss();
                    solveMessage(message);

                } else {
                    Intent intent = new Intent(App.getContext(), AddFriendMessageActivity.class);
                    intent.putExtra("MessageType", messageType);
                    intent.putExtra("messageId", message.getObjectId());
                    startActivity(intent);
                    popupWindow.dismiss();
                }


            }
        });
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {  //我直接忽略
                popupWindow.dismiss();
                solveMessage(message);
            }
        });
        popupWindow.showAtLocation(findViewById(android.R.id.content).getRootView(), Gravity.CENTER, 0, 0);

    }

    /**
     * 当侧滑菜单被打开时，回退键作用于侧滑菜单
     */
    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case R.id.nav_theme:
                App.ThemeControl = !App.ThemeControl;
                recreate();
                break;
            case R.id.nav_settings:
                startActivity(new Intent(MainActivity.this, SettingActivity.class));
                break;
            case R.id.nav_aboutme:
                //todo 测试用户信息入口
                // startActivity(new Intent(MainActivity.this, UserInfoActivity.class));
                //   MyToast.showToast("暂时不实现");
                Intent intent = new Intent(MainActivity.this, AddFriendActivity.class);
                intent.putExtra("isMe", true);
                startActivity(intent);
                break;
            case R.id.nav_friend:
                startActivity(new Intent(MainActivity.this, FriendListActivity.class));
                // MyToast.showToast("暂时还未实现");
                break;
            case R.id.nav_logout:

                BmobUser.logOut();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                finish();
                break;
            case R.id.nav_helpme:
                helpMe();
                break;

        }
        mDrawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }


    /**
     * 发送求救信息
     */
    private void helpMe() {
        final User currentUser = BmobUser.getCurrentUser(User.class);
        final FriendMessage friendMessage = new FriendMessage();
        friendMessage.setUser_id(currentUser.getObjectId());
        friendMessage.setAuthor_name(currentUser.getNickname());
        friendMessage.setComment_num(0);
        friendMessage.setLike_num(0);
        friendMessage.setCityname(currentUser.getCity());
        friendMessage.setAddress("点击查看我的位置");
        friendMessage.setAddress_latlan(mLatLng);
        friendMessage.setUser_icon(currentUser.getPortrait().getFileUrl());
        friendMessage.setContent("SOS,我遇到了危险，请点击地址查看我的位置");
        friendMessage.setTime(System.currentTimeMillis());
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.timg);
        final File file = ImageUtils.bitmap2File(bitmap, "helpme.png");
        final BmobFile bmobFile = new BmobFile(file);
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    friendMessage.setPicture(bmobFile);
                    friendMessage.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                loadMessage(currentUser);
                                MyToast.showToast("保存成功");

                            } else {
                                MyToast.showToast(e.toString());
                            }
                        }
                    });
                } else {
                    MyToast.showToast(e.toString());
                }
            }
        });


    }

    /**
     * 给该用户的所有好友发送一条信息
     *
     * @param currentUser
     */
    private void loadMessage(final User currentUser) {
        BmobQuery<Friend> friendBmobQuery = new BmobQuery<>();
        friendBmobQuery.addWhereEqualTo("userid", currentUser.getObjectId());
        friendBmobQuery.findObjects(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if (list != null && list.size() > 0) {
                    for (Friend friend : list) {
                        Message message = new Message();
                        message.setOther_userid(friend.getUserid());
                        message.setUserid(currentUser.getObjectId());  //给所有的好友
                        message.setMessagetime(System.currentTimeMillis());
                        message.setNickname(currentUser.getNickname());
                        message.setMessageType(MessageTypeUtils.MESSGE_HELP);
                        message.setContent("SOS,我遇到了危险" + currentUser.getNickname() + "赶紧来帮我啊 ！！！！");
                        message.setSolve(false);
                        message.setOther_userid(currentUser.getObjectId());
                        message.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if (e == null) {
                                    ALog.d("上传成功");
                                    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                                        mDrawerLayout.closeDrawer(GravityCompat.START);
                                    }
                                } else {
                                    ALog.d(e.toString());
                                    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                                        mDrawerLayout.closeDrawer(GravityCompat.START);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * Fab的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        startActivity(new Intent(MainActivity.this, SendMessageActivity.class));
        //MyToast.showToast("暂时不实现");
    }

    /**
     * 加载主界面的布局和数据
     */
    private void loadData() {
        mTabTitles = new String[]{"搭伙好友", "兴趣爱好", "附近的人"};
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setTitle(mTabTitles[0]);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(new FriendFragment());
        fragments.add(new HobbiesFragment());
        fragments.add(new NeigborFragment());
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        myPagerAdapter.setFragments(fragments);
        myPagerAdapter.setTabTitles(mTabTitles);
        mViewpager.setAdapter(myPagerAdapter);
        mTablayout.setupWithViewPager(mViewpager, false);
        mTablayout.setTabTextColors(getResources().getColor(R.color.gray), getResources().getColor(R.color.white));
        mTablayout.addOnTabSelectedListener(mOnTabSelectedListener);
        mViewpager.addOnPageChangeListener(mOnPageChangeListener);
        listenData();
    }

    public void initData() {
        User currentUser = BmobUser.getCurrentUser(User.class);
        BmobFile portrait = currentUser.getPortrait();
        if (portrait != null) {
            ALog.d("fileUrl" + portrait.getUrl());
            ALog.d("Url" + portrait.getFileUrl());
            GlideUtils.loadImage(MainActivity.this, portrait.getFileUrl(), mPortrait);
            mNickName.setText(currentUser.getNickname());
            mSign.setText(currentUser.getSign());
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }


    public void listenData() {
        final BmobRealTimeData rtd = new BmobRealTimeData();
        rtd.start(new ValueEventListener() {
            @Override
            public void onDataChange(JSONObject data) {
                Log.d("bmob", "(" + data.optString("action") + ")" + "数据：" + data);
            }

            @Override
            public void onConnectCompleted(Exception ex) {
                Log.d("bmob", "连接成功:" + rtd.isConnected());
            }
        });
    }

    /**
     * 位置信息的监听
     */
    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                mLatLng = new LatLng(latitude, longitude);
                Address address = location.getAddress();
            }


        }
    }

    /**
     * 处理消息,目前的方式是 从列表中删除
     *
     * @param localMessage
     */
    private void solveMessage(Message localMessage) {
        if (localMessage != null) {
            localMessage.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        ALog.d("删除成功");
                    } else {
                        ALog.d("删除不成功");
                    }
                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mLocationClient.stop();
    }


}
